#include "stm32f10x.h"   // Device header
#include "Delay.h"

void Sonic_Init()
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;   
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
 
	GPIO_InitStructure.GPIO_Pin =GPIO_Pin_0; //Trig 
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//推挽输出
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	GPIO_ResetBits(GPIOB ,GPIO_Pin_0);
	 
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;  //Echo   
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
	GPIO_Init(GPIOB, &GPIO_InitStructure);  
	GPIO_ResetBits(GPIOB, GPIO_Pin_1);    
	 
				
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);   
	 
	TIM_DeInit(TIM3);
	TIM_TimeBaseStructure.TIM_Period = (1000-1); 
	TIM_TimeBaseStructure.TIM_Prescaler =(72-1); 
	TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);          
			
	TIM_ClearFlag(TIM3, TIM_FLAG_Update);  
	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); 
	
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;             
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;         
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;       
	NVIC_Init(&NVIC_InitStructure);
	
	TIM_Cmd(TIM3,DISABLE);   
}

u16 overcount = 0;



//打开定时器3
static void OpenTimerForHc()  
{
   TIM_SetCounter(TIM3,0);
   overcount = 0;
   TIM_Cmd(TIM3, ENABLE); 
}
 
//关闭定时器3
static void CloseTimerForHc()    
{
   TIM_Cmd(TIM3, DISABLE); 
}

u32 GetEchoTimer(void)
{
   u32 t = 0;
   t = overcount*1000;
   t += TIM_GetCounter(TIM3);
   TIM3->CNT = 0;  //计数器归零
   Delay_ms(50);
   return t;
}

//TIM3中断
void TIM3_IRQHandler(void)  
{
   if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)  
   {
       TIM_ClearITPendingBit(TIM3, TIM_IT_Update); 
       overcount++; //计数器开始加
   }
}

float Sonic_Distance()
{
	float distance = 0, sum = 0;
	u32 time = 0;
	int i = 0;
	u8 k;
	
	while(i != 5)
	{
		for(k = 0; k < 5; k++)
		{
			GPIO_SetBits(GPIOB, GPIO_Pin_0);
			Delay_us(20);
			GPIO_ResetBits(GPIOB, GPIO_Pin_0);
		}

		while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0);
		
		OpenTimerForHc(); //开启定时器定时
		i += 1;
		while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 1);
		CloseTimerForHc();//关闭定时器定时
		
		time = GetEchoTimer(); //获取计TIM3寄存器中的计数值
		distance = (float)time/58.0; //通过回响信号计算距离
		sum = distance + sum;
	}
	distance = sum / 5;//计算5次的平均值
	return distance;
}


